layui.use(['element', 'jquery'], function(){
    var element = layui.element;
    var $       = layui.$;

    new parent.window._dom().setData('jQuery',$);
    var active = {
        tabAdd: function (url, id, name) {
            var id = id || $('.layui-tab-title li').length+1;
            //新增一个Tab项
            element.tabAdd('menu', {
                title: name, 
                content: '<iframe data-frameid="'+id+'" frameborder="0" name="content" scrolling="no" width="100%" src="' + url + '"></iframe>', 
                id: id
            });
            this.tabChange(id);
            FrameWH();//计算框架高度
        }
        , tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange('menu', id); //切换到data-frameid = id 的选项
            // $("iframe[data-frameid='"+id+"']").attr("src",$("iframe[data-frameid='"+id+"']").attr("src"))//切换后刷新框架
            whichIframe();
        }
        , tabDelete: function (id) {
            element.tabDelete("menu", id);//删除
            whichIframe();
        }
        , tabDeleteAll: function (ids) {//删除所有
            $.each(ids, function (i,item) {
                element.tabDelete("menu", item);
            })
        }
    };

    $(".layui-side-scroll a").click(function () {
        tabRelation($(this));
    });

    function tabRelation($dataid) {
        if ($dataid.hasClass('noTab')) return;
        $dataid.attr('data-id', $dataid.attr('data-id') || $(".layui-tab-title li").length);
        if ($(".layui-tab-title li[lay-id]").length <= 0) {
            active.tabAdd($dataid.attr("data-url"), $dataid.attr("data-id"), $dataid.text());
        } else {
            var isData  = false;
            var flag    = false;
            $.each($(".layui-tab-title li[lay-id]"), function () {
                if ($(this).attr("lay-id") == $dataid.attr("data-id")) {
                    if ( $(this).hasClass('layui-this') ) flag = true;   // 重复点击当前打开Tab 不触发后续事件
                    isData = true;
                }
            })
            if ( !isData ) {
                active.tabAdd($dataid.attr("data-url"), $dataid.attr("data-id"), $dataid.text());
            } else if ( flag ) return;
        }
        active.tabChange($dataid.attr("data-id"));
    };

    function FrameWH() {
        var h = $(window).height()-60-20-41-44;
        var $iframe = $("iframe");
        $iframe.css({
            "min-height":h+"px"
        });
    };

    $(window).resize(function () {
        FrameWH();
    });

    function whichIframe() {
        $('.layui-body')[0].scrollTo(0, 0);
        var tables = $($('iframe[data-frameid='+$('li.layui-this').attr('lay-id')+']')[0].contentDocument).find('table.canScroll');
        if ( tables[0] ) tableHeaderFixed($, $(tables[0]), 0, true);
        if ( tables[1] ) tableHeaderFixed($, $(tables[1]), 1);
    };

});
